package com.hzt.agprosaleplatform.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzt.agprosaleplatform.common.CustomResponse;
import com.hzt.agprosaleplatform.entity.Order;
import com.hzt.agprosaleplatform.entity.OrderCreateDTO;
import com.hzt.agprosaleplatform.entity.OrderItem;
import com.hzt.agprosaleplatform.entity.OrderDetailDTO;
import com.hzt.agprosaleplatform.mapper.OrderItemMapper;
import com.hzt.agprosaleplatform.mapper.OrderMapper;
import com.hzt.agprosaleplatform.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    //单个店铺-创建订单
    @Override
    @Transactional(rollbackFor = Exception.class) //事务管理
    public Order createOrder(OrderCreateDTO orderDTO) {
        Order order = new Order();
        order.setBuyer_id(orderDTO.getBuyer_id());
        order.setShop_id(Integer.parseInt(orderDTO.getShop_id()));//一个订单只能买一家店铺的，无法多供应商
        order.setAddress_id(orderDTO.getAddress_id());
        order.setOrder_message(orderDTO.getOrder_message());
        order.setStatus(0);  //默认创建为"未付款0"状态
        order.setPayment_method(order.getPayment_method());  //设置支付方式

        //计算总金额
        float totalPrice = orderDTO.getItems().stream()
                .map(item -> item.getUnit_price() * item.getAmount())
                .reduce(0f, Float::sum);
        order.setTotal_amount(totalPrice);

        Timestamp now = new Timestamp(System.currentTimeMillis());
        order.setCreated_date(now);
        order.setUpdate_date(now);


        orderMapper.insert(order);

        for (OrderCreateDTO.OrderItemDTO itemDTO : orderDTO.getItems()) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOid(order.getOid());
            orderItem.setGid(itemDTO.getGid());
            orderItem.setAmount(itemDTO.getAmount());
            orderItem.setUnit_price(itemDTO.getUnit_price());
            orderItem.setSub_total(itemDTO.getUnit_price()*itemDTO.getAmount());
//            orderItem.setTotal_price(itemDTO.getG_price() * totalPrice);
            orderItemMapper.insert(orderItem); //对商品-订单关联表作插入操作
        }

        return order;
    }

    //查询UID下的所有订单
    @Override
    public List<Order> selectOrderByUid(String uid) {
        return orderMapper.selectOrderByUid(uid);
    }

    @Override
    public List<Order> selectOrderByShopId(Integer shopId) {
        return orderMapper.selectOrderByShopId(shopId);
    }

    @Override
    public boolean updateOrderStatus(Integer oid, Integer status) {
        return orderMapper.updateOrderStatus(oid, status);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CustomResponse deleteOrder(Integer oid) {
        try {
            // 检查订单是否存在
            Order order = orderMapper.selectOrderByOid(oid);
            if (order == null) {
                return new CustomResponse(404, "订单不存在", null);
            }
            
            // 1:取消订单, 4:已完成, 5:退款
            int status = order.getStatus();
            if (status == 1 || status == 4 || status == 5) {
                // 删除订单-商品关联表中的商品数据
                orderItemMapper.deleteByOid(oid);
                // 再删除订单表的表数据
                orderMapper.deleteById(oid);
                return new CustomResponse(200, "删除订单成功", null);
            } else {
                return new CustomResponse(500, "订单未完成或处理中，无法删除", null);
            }
        } catch (Exception e) {
            return new CustomResponse(500, "删除订单失败: " + e.getMessage(), null);
        }
    }

    @Override
    public List<OrderDetailDTO> getOrderDetailsByUid(String uid) {
        try {
            // 从数据库获取订单详情
            List<OrderDetailDTO> orderDetailDTOS = orderMapper.selectOrderDetailsByUid(uid);
            
            if (orderDetailDTOS == null) {
                return new ArrayList<>();
            }

            // [DEBUG LOGGING] Log the details of fetched orders
            log.info("--- Debugging Order Details for UID: {} ---", uid);
            for (OrderDetailDTO orderDetail : orderDetailDTOS) {
                if (orderDetail.getStatus() == 3) { // Log only for shipped orders
                    log.info("Found SHIPPED Order -> Order ID: {}, Shop ID: {}, Address ID: {}", 
                             orderDetail.getOid(), orderDetail.getShop_id(), orderDetail.getAddress_id());
                }
            }
            log.info("--- End of Order Details Debug ---");

            // 处理每个订单中的tags字段
            for (OrderDetailDTO orderDetail : orderDetailDTOS) {
                if (orderDetail.getGoods() != null) {
                    for (OrderDetailDTO.GoodsItemDTO goodsItem : orderDetail.getGoods()) {
                        String tagsStr = goodsItem.getTagsStr();
                        if (tagsStr != null && !tagsStr.isEmpty()) {
                            goodsItem.setTags(Arrays.asList(tagsStr.split(",")));
                        } else {
                            goodsItem.setTags(new ArrayList<>());
                        }
                    }
                }
            }
            return orderDetailDTOS;
        } catch (Exception e) {
            throw new RuntimeException("获取订单详情失败", e);
        }
    }
    
    @Override
    public Map<String, Object> getShopOrderStatistics(Integer shopId) {
        Map<String, Object> statistics = new HashMap<>();
        
        // 获取订单总数
        int totalOrders = orderMapper.countOrdersByShopId(shopId);
        statistics.put("totalOrders", totalOrders);
        
        // 获取总收入
        Double totalRevenue = orderMapper.sumOrderAmountsByShopId(shopId);
        statistics.put("totalRevenue", totalRevenue != null ? totalRevenue : 0.0);
        
        // 获取待处理订单数（状态为0待付款或2已付款）
        int pendingOrders = orderMapper.countPendingOrdersByShopId(shopId);
        statistics.put("pendingOrders", pendingOrders);
        
        return statistics;
    }
    
    @Override
    public List<Map<String, Object>> getShopRevenueTrend(Integer shopId) {
        return orderMapper.selectRevenueTrend(shopId);
    }
    
    @Override
    public List<Map<String, Object>> getShopOrderStatusStats(Integer shopId) {
        return orderMapper.selectOrderStatusStats(shopId);
    }
}